#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
import requests
from utils.session_mc import get_mc, set_mc

weixin_token = 'shitouren'
weixin_appid = 'wxbc10fc8f17652407'
weixin_secret = '94d2c225543345a52031af10df38b805'
weixin_ticket_mc_key = 'wx_jsticket'
weixin_ticket_expire = 3600
weixin_noncestr = "Yk5MAZOTc1wzccnW"

def get_access_token():
    url = 'https://api.weixin.qq.com/cgi-bin/token'
    payload = {
        'grant_type': 'client_credential',
        'appid': weixin_appid,
        'secret': weixin_secret,
    }

    res = requests.get(url, params=payload)

    if res.status_code != 200:
        return None

    access_token = res.json().get('access_token', None)
    return access_token


def refresh_weixin_ticket():
    url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'
    payload = {
        'access_token': get_access_token(),
        'type': 'jsapi',
    }

    res = requests.get(url, params=payload)

    if res.status_code != 200:
        return None

    return res.json().get('ticket', None)

def get_weixin_ticket():
    weixin_ticket = get_mc(weixin_ticket_mc_key)

    if not weixin_ticket:
        weixin_ticket = refresh_weixin_ticket()
        set_mc(weixin_ticket_mc_key, weixin_ticket, weixin_ticket_expire)

    return weixin_ticket


def get_signature(noncestr, timestamp, url):
    string1 = 'jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s'\
              % (get_weixin_ticket(), noncestr, timestamp, url)

    sha1 = hashlib.sha1()
    sha1.update(string1)
    return sha1.hexdigest()


if __name__ == '__main__':
    print get_weixin_ticket()